import json
import logging
import random
import time
import uuid
from datetime import datetime, timedelta
from loguru import logger

from faker import Faker
from Common.global_data import GlobalData

"""
定义代码生成的数据
需要什么生成数据的函数，就定义什么
"""

faker = Faker("zh-CN")


def random_str():
    res = faker.pystr(min_chars=4, max_chars=4)
    return res


def cur_time():
    return str(int(time.time() * 1000))


def random_past_datetime():
    # 随机生成已经过去的时间
    # 新版本faker会生成毫秒，需要转一下格式
    p_time = faker.past_datetime().strftime('%Y-%m-%d %H:%M:%S')
    expirationTime = datetime.strptime(p_time, "%Y-%m-%d %H:%M:%S").strftime('%Y-%m-%dT%H:%M:%S')
    setattr(GlobalData, "expirationTime", expirationTime)
    return p_time


def random_future_datetime():
    # 随机生成未来的时间
    # 新版本faker会生成毫秒，需要转一下格式
    f_time = faker.future_datetime().strftime('%Y-%m-%d %H:%M:%S')
    expirationTime = datetime.strptime(f_time, "%Y-%m-%d %H:%M:%S").strftime('%Y-%m-%dT%H:%M:%S')
    setattr(GlobalData, "expirationTime", expirationTime)
    return f_time


def random_datetime():
    # 随机生成时间
    # 新版本faker会生成毫秒，需要转一下格式
    r_time = faker.date_time().strftime('%Y-%m-%d %H:%M:%S')
    expirationTime = datetime.strptime(r_time, "%Y-%m-%d %H:%M:%S").strftime('%Y-%m-%dT%H:%M:%S')
    setattr(GlobalData, "expirationTime", expirationTime)
    return r_time


def gen_uuid():
    res = uuid.uuid4()
    setattr(GlobalData, "uuid", str(res))
    return str(res)


def random_phone():
    recharge_phone = faker.phone_number()
    setattr(GlobalData, "recharge_phone", recharge_phone)

    return recharge_phone


def random_recharge_orderno():
    # 车企直充随机订单号，前面加个999做区分
    business_id = "999" + cur_time()
    setattr(GlobalData, "business_id", business_id)
    return business_id


def all_product_id_list():
    product_info_list = getattr(GlobalData, "product_info_list")
    return str([item["id"] for item in eval(product_info_list)])


def all_product_id_list_except_iqiyi():
    product_info_list = getattr(GlobalData, "product_info_list")
    product_iqiyi_id = getattr(GlobalData, "product_iqiyiapp_id")
    return str([item["id"] for item in eval(product_info_list) if item["id"] != product_iqiyi_id])


def random_sn():
    # 激活的设备sn号
    # activate_sn = faker.pystr(min_chars=12, max_chars=12)
    rid_sn = "RIDauto" + faker.md5()
    aid_sn = "AIDauto" + faker.md5()

    activate_sn = random.choice([rid_sn, aid_sn])
    setattr(GlobalData, "activate_sn", activate_sn)
    return activate_sn


def random_vin():
    # 激活的设备vin号
    # activate_sn = faker.pystr(min_chars=12, max_chars=12)
    activate_vin = "autoVIN" + faker.pystr(min_chars=5, max_chars=5)
    setattr(GlobalData, "activate_vin", activate_vin)
    return activate_vin


def random_version():
    # 激活的版本号
    # activate_sn = faker.pystr(min_chars=12, max_chars=12)
    activate_version = "v{}.{}.{}".format(faker.random_digit_not_null(), faker.random_digit(), faker.random_digit())
    setattr(GlobalData, "activate_version", activate_version)
    return activate_version


def random_md5():
    cur_md5 = faker.md5()
    setattr(GlobalData, "cur_md5", cur_md5)
    return cur_md5


# def random_cp_appifo():
#     appinfo = {"dataReporting": "", "contentProviders": {
#         "IQIYI": [{"md5": faker.md5(), "packages": ["com." + faker.domain_name(), "com." + faker.domain_name()]},
#                   {"md5": faker.md5(), "packages": ["com." + faker.domain_name(), "com." + faker.domain_name()]}],
#         "MGTV": [{"md5": faker.md5(), "packages": ["com." + faker.domain_name()]}]}}
#     appinfo_dumps = json.dumps(appinfo, ensure_ascii=False)
#     appinfo_dumps_str = json.dumps(appinfo, ensure_ascii=False).replace('"', '\\"')
#     setattr(GlobalData, "cur_cp_appifo", appinfo_dumps)
#     return appinfo_dumps_str


def random_cp_appifo():
    appinfo = {"dataReporting": "", "contentProviders": [
        {"cpName": "IQIYI", "cpInfo": [
            {"md5": faker.md5(), "packages": ["com." + faker.domain_name(), "com." + faker.domain_name()]},
            {"md5": faker.md5(), "packages": ["com." + faker.domain_name(), "com." + faker.domain_name()]}]},
        {"cpName": "MGTV", "cpInfo": [{"md5": faker.md5(), "packages": ["com." + faker.domain_name()]}]}]}

    appinfo_dumps = json.dumps(appinfo, ensure_ascii=False)
    appinfo_dumps_str = json.dumps(appinfo, ensure_ascii=False).replace('"', '\\"')
    setattr(GlobalData, "cur_cp_appifo", appinfo_dumps)
    return appinfo_dumps_str


def random_yaml_name():
    # cur_yaml_name = faker.pystr(min_chars=6, max_chars=6) + ".yaml"
    cur_yaml_name = faker.word() + faker.word() + faker.word() + ".yaml"
    setattr(GlobalData, "cur_yaml_name", cur_yaml_name)

    return cur_yaml_name


def random_pic_name():
    # cur_yaml_name = faker.pystr(min_chars=6, max_chars=6) + ".yaml"
    cur_yaml_name = faker.word() + faker.word() + faker.word() + ".jpg"
    setattr(GlobalData, "cur_pic_name", cur_yaml_name)

    return cur_yaml_name


def add_app_to_FiveDBusinessTree():
    new_app = [{"code": getattr(GlobalData, "account_id_new"), "type": 1},
               {"code": getattr(GlobalData, "project_id"), "type": 2,
                "parentCode": getattr(GlobalData, "account_id_new")},
               {"code": getattr(GlobalData, "product_app_id"), "type": 3,
                "parentCode": getattr(GlobalData, "project_id")}]
    logger.info(f"组装的new_app:{new_app}")
    FiveDBusinessTree = getattr(GlobalData, "FiveDBusinessTree")
    # FiveDBusinessTree.extend(new_app)
    # new_app.extend(FiveDBusinessTree)
    res = FiveDBusinessTree + new_app
    return json.dumps(res)


def add_app_to_FiveDBusinessTree_continue():
    new_app = [
        {"code": getattr(GlobalData, "product_app_id"), "type": 3,
         "parentCode": getattr(GlobalData, "project_id")}]
    logger.info(f"组装的new_app:{new_app}")
    FiveDBusinessTree = getattr(GlobalData, "FiveDBusinessTree")
    # FiveDBusinessTree.extend(new_app)
    # new_app.extend(FiveDBusinessTree)
    res = FiveDBusinessTree + new_app
    return json.dumps(res)


def add_app_to_CmsBusinessTree():
    new_app = [{"code": getattr(GlobalData, "account_id_new"), "type": 1},
               {"code": getattr(GlobalData, "project_id"), "type": 2,
                "parentCode": getattr(GlobalData, "account_id_new")},
               {"code": getattr(GlobalData, "product_app_id"), "type": 3,
                "parentCode": getattr(GlobalData, "project_id")}]
    logger.info(f"组装的new_app:{new_app}")
    CmsBusinessTree = getattr(GlobalData, "CmsBusinessTree")
    # FiveDBusinessTree.extend(new_app)
    # new_app.extend(FiveDBusinessTree)
    res = CmsBusinessTree + new_app
    return json.dumps(res)


def add_app_to_CmsBusinessTree_and_open_all_channell():
    new_app = [{"code": getattr(GlobalData, "account_id_new"), "type": 1},
               {"code": getattr(GlobalData, "project_id"), "type": 2,
                "parentCode": getattr(GlobalData, "account_id_new")},
               {"code": getattr(GlobalData, "product_app_id"), "type": 3,
                "parentCode": getattr(GlobalData, "project_id")},
               {"code": "-1", "type": 4,
                "parentCode": getattr(GlobalData, "product_app_id")},
               {"code": "1", "type": 4,
                "parentCode": getattr(GlobalData, "product_app_id")},
               {"code": "15", "type": 4,
                "parentCode": getattr(GlobalData, "product_app_id")},
               {"code": "2", "type": 4,
                "parentCode": getattr(GlobalData, "product_app_id")},
               {"code": "3", "type": 4,
                "parentCode": getattr(GlobalData, "product_app_id")},
               {"code": "4", "type": 4,
                "parentCode": getattr(GlobalData, "product_app_id")},
               {"code": "6", "type": 4,
                "parentCode": getattr(GlobalData, "product_app_id")}
               ]
    logger.info(f"组装的new_app:{new_app}")
    CmsBusinessTree = getattr(GlobalData, "CmsBusinessTree")
    # FiveDBusinessTree.extend(new_app)
    # new_app.extend(FiveDBusinessTree)
    res = CmsBusinessTree + new_app
    return json.dumps(res)


class ContentData:
    cur_contentId_set = set()


def random_contentId():
    # cur_contentId = str(faker.random_number(digits=4))
    while True:
        cur_contentId = random.choice(
            ["5158427756414700", "7400481300774100", "8432868746771400", "5338915072173400", "5954978441244501"])
        if cur_contentId not in ContentData.cur_contentId_set:
            ContentData.cur_contentId_set.add(cur_contentId)
            setattr(GlobalData, "cur_contentId", cur_contentId)
            return cur_contentId


def random_applicableObjects():
    res = faker.pystr(min_chars=8, max_chars=8)
    setattr(GlobalData, "cur_applicableObjects", res)
    return res


def join_subTaskIds():
    subTaskIds = getattr(GlobalData, "subTaskIds")
    res = ','.join(subTaskIds)
    return res


def random_banner_name():
    cur_banner_name = "推荐内容_" + faker.word() + faker.word() + faker.word()
    setattr(GlobalData, "cur_banner_name", cur_banner_name)

    return cur_banner_name


def current_add_seconds():
    # 获取当前时间
    current_time = datetime.now()

    # 加上5秒
    future_time = current_time + timedelta(seconds=5)

    # 格式化输出
    formatted_time = future_time.strftime('%Y-%m-%d %H:%M:%S')

    return formatted_time


def get_bannerUrls():
    uploadId = getattr(GlobalData, "uploadId")
    subTaskIds = getattr(GlobalData, "subTaskIds")
    fileIds = getattr(GlobalData, "fileIds")
    pic_urls = getattr(GlobalData, "pic_urls")
    res = []
    for fileId, subTaskId, url in zip(fileIds, subTaskIds, pic_urls):
        res.append({
            "uploadId": uploadId,
            "subTaskId": int(subTaskId),
            "fileId": fileId,
            "url": url
        })
    # res = json.dumps(res)
    res_dumps_str = json.dumps(res, ensure_ascii=False).replace('"', '\\"')
    return res_dumps_str


def join_productIds():
    Year_product_id = getattr(GlobalData, "Year_product_id")
    Quarter_product_id = getattr(GlobalData, "Quarter_product_id")
    Mouth_product_id = getattr(GlobalData, "Mouth_product_id")
    res = ','.join([Year_product_id, Quarter_product_id, Mouth_product_id])
    return res


if __name__ == '__main__':
    res = random_contentId()
    print(res)

    pass
